﻿using System.Collections.Generic;
using UnityEngine;

public class SoldierFSMSystem
{
    private List<ISoldierState> mStates;
    private SoldierStateId mCurrStateId;
    public SoldierStateId CurrStateId => mCurrStateId;
    private ISoldierState mCurrState;
    public ISoldierState CurrState => mCurrState;

    public SoldierFSMSystem()
    {
        mStates = new List<ISoldierState>();
    }

    public void AddState(params ISoldierState[] states)
    {
        foreach (var state in states)
        {
            AddState(state);
        }
    }

    public void AddState(ISoldierState state)
    {
        if (state == null)
        {
            Debug.LogError("AddState: 当前状态为空！");
        }

        if (mStates.Count == 0)
        {
            mStates.Add(state);
            mCurrState = state;
            mCurrStateId = state.StateId;
            return;
        }

        foreach (ISoldierState myState in mStates)
        {
            if (myState.StateId == state.StateId)
            {
                Debug.LogError("AddState: 包含当前状态！请勿重复添加!");
                return;
            }
        }

        mStates.Add(state);
    }

    public void DeleteState(SoldierStateId stateId)
    {
        if (stateId == SoldierStateId.NullStateId)
        {
            Debug.LogError("DeleteState : 当前状态为空,无法删除!");
            return;
        }

        foreach (var state in mStates)
        {
            if (state.StateId == stateId)
            {
                mStates.Remove(state);
                return;
            }
        }

        Debug.LogError("DeleteState : 需要删除的 SoldierStateId 不存在!");
    }

    public void PerformTransition(SoldierTransition trans)
    {
        if (trans == SoldierTransition.NullTransition)
        {
            Debug.LogError("PerformTransition : 当前SoldierTransition为空");
            return;
        }

        SoldierStateId nextStateId = mCurrState.GetOutputState(trans);
        if (nextStateId == SoldierStateId.NullStateId)
        {
            Debug.LogError("PerformTransition : 当前SoldierStateId为空");
            return;
        }

        foreach (var state in mStates)
        {
            if (state.StateId == nextStateId)
            {
                mCurrState.DoBeforeLeaving();
                mCurrState = state;
                mCurrState.DoBeforeEntering();
                return;
            }
        }
    }
}